#!/usr/bin/python3
# -*- coding: UTF-8 -*-

import tempfile
import os
import re as osRe
import time
import xml.etree.cElementTree as ET
from xml.dom.minidom import parse
from os import popen as osPopen, path as osPath  # 管道处理

import gol

# 通过元素定位,需要Android 4.0以上
class Element():
    # 初始化，获取系统临时文件存储目录，定义匹配数字模式
    def __init__(self):
        self.sAdb = gol.get("sAdb")
        self.sPhonePathBase = "/sdcard"
        self.sPhoneDir = "tmp"
        self.sPCPath = "/private/tmp"
        self.rePattern = osRe.compile(r"\d+") 
        self.sSaveName = 'uidump.xml'

    # 获取当前Activity控件树
    def __uidump(self):
        # 抽出简化内容
        print("创建文件夹")
        osPopen('%s shell "[ ! -d %s ] && cd %s && mkdir %s"' % (self.sAdb, osPath.join(self.sPhonePathBase, self.sPhoneDir), self.sPhonePathBase, self.sPhoneDir))
        print("生成XML结构文件")
        oReUi = osPopen('%s shell uiautomator dump %s' % (self.sAdb, osPath.join(self.sPhonePathBase, self.sPhoneDir, self.sSaveName)))
        print(oReUi.readlines())
        # 写入sd卡
        print("拷贝文件")
        osPopen('%s pull %s %s' % (self.sAdb, osPath.join(self.sPhonePathBase,self.sPhoneDir,self.sSaveName), self.sPCPath))

    # 同属性单个元素，返回单个坐标元组
    def __element(self, attrib, name, isRe = False):
        self.__uidump()
        tree = ET.ElementTree(file=self.sPCPath + "/" + self.sSaveName)
        treeIter = tree.iter(tag="node")
        for elem in treeIter:
            if isRe == False:
                if elem.attrib[attrib] == name:
                    return self.__getPoint(elem)
            else:
                reVal = osRe.match("name", elem.attrib[attrib])
                if reVal != None:
                    return self.__getPoint(elem)

 
    def __getPoint(self, elem):
        bounds = elem.attrib["bounds"]
        coord = self.rePattern.findall(bounds)
        Xpoint = (int(coord[2]) - int(coord[0])) // 2 + int(coord[0])
        Ypoint = (int(coord[3]) - int(coord[1])) // 2 + int(coord[1])

        return Xpoint, Ypoint

    # 同属性多个元素，返回坐标元组列表
    def __elements(self, attrib, name):
        list = []
        # self.__uidump()
        tree = ET.ElementTree(file=self.sPCPath + "/" + self.sSaveName)
        treeIter = tree.iter(tag="node")
        for elem in treeIter:
            if elem.attrib[attrib] == name:
                bounds = elem.attrib["bounds"]
                coord = self.rePattern.findall(bounds)
                Xpoint = (int(coord[2]) - int(coord[0])) / 2.0 + int(coord[0])
                Ypoint = (int(coord[3]) - int(coord[1])) / 2.0 + int(coord[1])
                list.append((Xpoint, Ypoint))
        return list

    def init(self):
        self.__uidump()

    # 通过元素名称定位  usage: findElementByName(u"相机")
    def findElementByName(self, name):
        return self.__element("text", name)

    def findElementsByName(self, name):
        return self.__elements("text", name)

    # 通过元素类名定位  usage: findElementByClass("android.widget.TextView")
    def findElementByClass(self, className):
        return self.__element("class", className)

    def findElementsByClass(self, className):
        return self.__elements("class", className)

    # 通过元素的resource-id定位  usage: findElementsById("com.android.deskclock:id/imageview")
    def findElementById(self, id):
        return self.__element("resource-id", id)

    def findElementsById(self, id):
        return self.__elements("resource-id", id)

